//
//  RAPHomeTableViewController.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 12/27/15.
//  Copyright © 2015 RendezvousAuParadis. All rights reserved.
//

import UIKit
import SVProgressHUD

let kLatestCountLabelHeight: CGFloat = 30


class RAPHomeTableViewController: RAPVisitorViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        if !isLogin {
            visitorView.setupVisitorView("visitordiscover_feed_image_house", messageText: "看看这里都关注了谁，每天都有新鲜事。看看这里都关注了谁，每天都有新鲜事。", hasCircle: true)
            /*
            如果还为登录，则没有必要执行下面的逻辑
            */
            return
        }
        
        setupUI()

        pullUpRefreshIndicator.startAnimating()
        RAPStatusesListViewModel.sharedViewModel.loadStatuses { (isSuccess) -> () in
            if isSuccess == true {
                // 刷新数据
                self.tableView.reloadData()
                self.animateLatestCountLabel(RAPStatusesListViewModel.sharedViewModel.lastestStatusesCount!)
            } else {
                // 数据请求失败
                SVProgressHUD.showErrorWithStatus("数据请求失败")
            }
            self.pullUpRefreshIndicator.stopAnimating()
        }

    }
    
    private func setupUI() {
    navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: "friendSearchButtonClicked:")
    navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "popButtonClicked:")
        
        setupTableView()
    
    }
    
    ///  设置 table view
    func setupTableView() {
        // 注册cell
        tableView.registerClass(RAPStatusCell.self, forCellReuseIdentifier: "reuseIdentifier")
        
        // 预估行高
        tableView.estimatedRowHeight = 200

        tableView.rowHeight = UITableViewAutomaticDimension // 此行代码可省略
        tableView.separatorStyle = .None
        
        tableView.backgroundColor = UIColor(white: 237 / 255.0, alpha: 1)
        
        // 添加上拉刷新控件
        tableView.tableFooterView = pullUpRefreshIndicator
        
        // 添加下拉刷新控件
//        refreshControl = UIRefreshControl()
//        refreshControl!.addTarget(self, action: "refreshControlPulledDown", forControlEvents: UIControlEvents.ValueChanged)
        
        tableView.addSubview(pullDownRefreshControl)
        
        // 添加刷新提示控件
        navigationController?.view.insertSubview(latestCountLabel, belowSubview: (navigationController?.navigationBar)!)
        latestCountLabel.frame = CGRectMake(0, CGRectGetMaxY((navigationController?.navigationBar.frame)!) - kLatestCountLabelHeight, kScreenBounds.width, kLatestCountLabelHeight)
    }
    
    func friendSearchButtonClicked(sender: UIBarButtonItem) {
        RAPLog("friendSearchButtonClicked")
    }
    
    func popButtonClicked(sender: UIBarButtonItem) {
        RAPLog("popButtonClicked")
    }

    ///  下拉刷新动作方法
    @objc private func refreshControlPulledDown() {
        let id = RAPStatusesListViewModel.sharedViewModel.statusArray?.first?.statusModel.id
        RAPLog("下拉刷新请求\(id)")
        askForMoreStatuses(id!, kind: .New)
    }

    // MARK: - 懒加载控件
    /// 上拉获取以前微博
    private lazy var pullUpRefreshIndicator: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .White)
        indicator.color = UIColor.orangeColor()
        return indicator
    }()
    
    /// 下拉获取最新微博
    private lazy var pullDownRefreshControl: RAPPullDownRefreshControl = {
        let control = RAPPullDownRefreshControl()
        control.addTarget(self, action: "refreshControlPulledDown", forControlEvents: UIControlEvents.ValueChanged)
        return control
    }()
    
    private lazy var latestCountLabel: UILabel = {
        let latestCountLabel = UILabel(text: "", fontSize: 12)
        latestCountLabel.textAlignment = .Center
        latestCountLabel.textColor = UIColor.whiteColor()
        latestCountLabel.backgroundColor = UIColor.orangeColor()
        latestCountLabel.hidden = true
        return latestCountLabel
    }()
    
    // MARK: - 动作方法
    ///  实现最新微博提示数量的动画效果
    private func animateLatestCountLabel(count: Int) {
        /*
        如果在一个动画周期内这个方法多次被调用，
        则判断控件是否显示，如果显示，说明正在动画中，
        不再做动作
        */
        if latestCountLabel.hidden == false {
            return
        }
        
        latestCountLabel.text = count == 0 ? "Sorry，没有新的微博" : "为主人刷新了\(count)条微博"
        
        latestCountLabel.hidden = false
        UIView.animateWithDuration(0.75, animations: { () -> Void in
            // 动画效果
            self.latestCountLabel.transform = CGAffineTransformMakeTranslation(0, kLatestCountLabelHeight)
            }) { (_) -> Void in
                UIView.animateWithDuration(0.75, delay: 1, options: [], animations: { () -> Void in
                    self.latestCountLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.latestCountLabel.hidden = true
                })
        }
    }
    
    
    // MARK: - 数据加载方法
    ///  加载新的微博数据
    ///
    ///  - parameter statusID: 微博id
    ///  - parameter kind:     获取最新 / 以往微博数据
    private func askForMoreStatuses(statusID: Int64, kind: RAPLoadMoreStatuses) {
        
        var id: Int64?
        var kd: RAPLoadMoreStatuses?
        
        if kind == .New { // 获取最新微博
            id = statusID
            kd = .New
        } else if kind == .Past { // 获取以往微博
            id = statusID - 1
            kd = .Past

        }

        pullUpRefreshIndicator.startAnimating()
        RAPStatusesListViewModel.sharedViewModel.loadStatuses(id!, kind: kd!) { (isSuccess) -> () in
            if isSuccess == true {
                // 刷新数据
                self.tableView.reloadData()
                self.animateLatestCountLabel(RAPStatusesListViewModel.sharedViewModel.lastestStatusesCount!)
            } else {
                // 数据请求失败
                SVProgressHUD.showErrorWithStatus("数据请求失败")
            }
            self.pullUpRefreshIndicator.stopAnimating()
            
            // 系统下拉刷新控件
//            self.refreshControl?.endRefreshing()
            // 自定义下拉刷新控件
            self.pullDownRefreshControl.endRefreshing()
        }
    }
}

// MARK: - Table view data source
extension RAPHomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return RAPStatusesListViewModel.sharedViewModel.statusArray?.count ?? 0
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! RAPStatusCell
        
        // 取出每行对应的 RAPStatusCellViewModel
        let statusCellViewModel = RAPStatusesListViewModel.sharedViewModel.statusArray![indexPath.row]
        cell.statusCellViewModel = statusCellViewModel
        
        print(statusCellViewModel.tweetMessage);
        
        return cell
    }
}

// MARK: - UITableViewDelegate
extension RAPHomeTableViewController {
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        // 禁止多次刷新
        if pullUpRefreshIndicator.isAnimating() {
            return
        }
        
        let viewModel = RAPStatusesListViewModel.sharedViewModel
        
        if indexPath.row == (viewModel.statusArray?.count)! - 1 { // 滑动至最后一个
            
            
            let id = viewModel.statusArray![indexPath.row].statusModel.id
            
            askForMoreStatuses(id, kind: .Past)
        }
        
        
    }
}
